<?php
// +-------------------------------------------------------------------------------
// | DingZone [ A Rapid Development Framework For Dingtalk ]
// +-------------------------------------------------------------------------------
// | 企业相关API调用Controller v1.0
// |
// | Copyright (c) 2014-2018 http://www.heimalanshi.com All rights reserved.
// | Author : Jie
// | Date : 2018-08-09
// +-------------------------------------------------------------------------------

namespace app\core\controller\enterprise;

use ding\ApiHelper;
use think\App;
use think\Request;

/**
 * 企业模块Api调用
 *
 * @package app\core\controller\enterprise
 */
class ApiController extends EnterpriseBaseController {

    /**
     * 调用api
     *
     * @param $apiName
     * @throws \Exception
     */
    public function call($apiName) {
        $mid = input("get.mid");
        $apiArgs = Request::instance()->post();

        // api对象
        if ($this->_isEnterpriseAdmin() || $this->_isModuleAdmin($mid)) {
            // 企业管理员或者模块管理员，可以不受api权限限制
            $apiHelper = new ApiHelper($this->enterprise, null);
        } else {
            $apiHelper = $this->_getApiHelper($mid);
        }

        // 反射获取对应的方法
        $ref = new \ReflectionClass(get_class($apiHelper));
        $method = $ref->getMethod($apiName);
        // 拼装方法参数
        $parameters = $method->getParameters();
        $args = [];
        foreach ($parameters as $parameter) {
            $name = $parameter->getName();
            if (isset($apiArgs[$name])) {
                $args[] = $apiArgs[$name];
            } else {
                $args[] = $parameter->getDefaultValue();
            }
        }
        // 反射调用
        $response = $method->invokeArgs($apiHelper, $args);
        $this->result([
            'response' => $response,
            'lastStatus' => $apiHelper->getLastStatus()
        ], 1);
    }

    /**
     * 自定义错误信息
     *
     * @param string $msg
     * @param null $url
     * @param string $data
     * @param int $wait
     * @param array $header
     */
    protected function error($msg = '', $url = null, $data = '', $wait = 3, array $header = []) {
        $this->result([
            'response' => $data,
            'lastStatus' => array(
                'errcode' => -99999,
                'errmsg' => $msg
            )
        ], 0, $msg);
    }


}